<?php
namespace Controllers;
use Resources, Libraries;
class Auth extends Resources\Controller {
    public function __construct() {
        parent::__construct();
        $this->request = new Resources\Request;
        $this->session = new Resources\Session;
    }
    public function login() {

        if (Libraries\u::isAjaxRequest()) {
            $msg = 'Username atau password salah.';
            $username = $this->request->post('loginUsername', FILTER_SANITIZE_MAGIC_QUOTES);
            $password = $this->request->post('loginPassword', FILTER_SANITIZE_MAGIC_QUOTES);
            if ($password != '' && $username != '') {
                $this->db = new Libraries\Mysql;
                $user = $this->db->row("SELECT id_user,password FROM psn_users where username = '$username'");
                if ($user != null) {
                    if (Libraries\bCrypt::verify($password, $user->password)) {
                        $this->session->regenerateId();
                        $this->session->setValue(array('islogin' => true, 'user_id' => $user->id_user));
                        $this->outputJSON(array('success' => 'true'));
                    } else {
                        $this->outputJSON(array('success' => 'false', 'msg' => $msg));
                    }
                } else {
                    $this->outputJSON(array('success' => 'false', 'msg' => $msg));
                }
            } else {
                $this->outputJSON(array('success' => 'false', 'msg' => $msg));
            }
        } else {
            $data['title'] = 'Login';
            $this->output('login', $data);
        }
    }
    public function logout() {
        $this->session->destroy();
        $this->redirect('auth/login');
    }
}
